<?php
/**
 * Created by PhpStorm.
 * User: an
 * Date: 2015/8/11
 * Time: 11:14
 */
namespace app\index\domain;


use app\index\domain\BaseDomain;
use app\extend\Check;
use app\shop\api\AddressApi;
use app\shop\api\MemberConfigApi;
use app\system\api\MemberApi;
use app\system\api\UserLogApi;

class AddressDomain extends BaseDomain{
    protected $business_code = 'address';
    // function getSupportMethod(){
    // }

    /**
     * 添加收货地址
     */
    public function add(){
        $this->checkVersion(101);
        addLog("Address/add",$_GET,$_POST,"应用" . $this->client_id . "调用Address添加接口");

        $uid     = $this->_post("uid",0,"UID不能为空");
        $default = $this->_post("default",0);
        $map = ['uid'=>$uid];
        $result = apiCall(AddressApi::GET_INFO,[$map]);
        $arr = ['err'=>[],'suc'=>[]];
        if($result['status']){
           if(empty($result['info'])){
              $default = 1;
              //+score  +exp
              $result = apiCall(UserLogApi::FIRST_ADDRESS,[$uid]);
              if(!$result['status']) $this ->apiReturnErr($result['info']);
              $arr = $result['info'];
           }
        }

        $map = $this->getAddressModel();
        $map['uid'] = $uid;
        $result = apiCall(AddressApi::ADD,[$map]);
        if($result['status']){
            $aid = intval($result['info']);
            if(1 === intval($default)){
                $this->setDefaultAid($uid,$aid);
            }
            $this->apiReturnSuc(['id'=>''.$aid,'msg'=>$arr]);
        }else{
            $this->apiReturnErr("添加失败");
        }
    }


    /**
     * 查看收货地址
     */
    public function queryNoPaging(){
        $this->checkVersion($this->api_ver);
        $notes = "应用".$this->client_id."，调用Address查询接口";
        addLog("Address/add",$_GET,$_POST,$notes);
        $uid = intval($this->_post('uid',0,"用户ID缺失"));
        $map = ['uid'=>$uid];

        //查询默认地址
        $aid    = $this->getAidByUid($uid);
        $result = apiCall(AddressApi::QUERY_NO_PAGING,[$map," id desc "]);
        if($result['status']){
            if(empty($result['info'])){
                $result['info'] = [];
            }else{
                foreach ($result['info'] as $k=>$v) {
                    if(intval($v['id']) == $aid){
                        $result['info'][$k]['default'] = 1;
                    }else{
                        $result['info'][$k]['default'] = 0;
                    }
                }
            }
            $this->apiReturnSuc($result['info']);
        }else{
            $this->apiReturnErr("查询失败");
        }

    }

    // /**
    //  * 查看收货地址
    //  */
    // public function queryWithCityWithArea(){

    //     $this->checkVersion(100);
    //     addLog("Address/queryWithCityWithArea",$_GET,$_POST,"应用" . $this->client_id . "调用Address查询接口");


    //     $map=array(
    //         'uid'=>$this->_post('uid',0,"用户ID不能为空"),
    //     );

    //     $order="default_address desc";
    //     $result=apiCall(AddressApi::QUERY_WITH_CITY_WITH_AREA,array($map,$order));
    //     if($result['status']){
    //         $this->apiReturnSuc($result['info']);
    //     }else{
    //         $this->apiReturnErr("查询失败");
    //     }

    // }

    //设置默认地址的接口
    public function setDefault(){
        $this->checkVersion($this->api_ver);
        addLog("Address/setDefaultAddress",$_GET,$_POST,"应用" . $this->client_id . "调用Address设置默认地址接口");

        $uid = $this->_post('uid',0,"用户ID不能为空");
        $id  = $this->_post('id','',"地址ID不能为空");
        $map = [
            'uid'             =>$uid,
            'default_address' =>$id,
        ];
        $result = apiCall(AddressApi::GET_INFO,[['id'=>$id,'uid'=>$uid]]);
        if(!$result['status']) $this->apiReturnErr("系统错误");
        if(empty($result['info']))  $this->apiReturnErr("无此用户或地址");
        $this->setDefaultAid($uid,$id);
        $this->apiReturnErr("设置成功");
    }

    //获取默认收货地址ID
    public function getDefault(){
        $this->checkVersion($this->api_ver);
        addLog("Address/getDefaultAddress",$_GET,$_POST,"应用" . $this->client_id . "调用Address获取默认地址接口");
        $uid = intval($this->_post('uid',0,"用户ID不能为空"));
        $aid = $this->getAidByUid($uid);
        if($aid){
            $map    = ['uid' => $uid,'id'=>$aid];
            $result = apiCall(AddressApi::GET_INFO,[$map]);
        }else{
            $map    = ['uid' => $uid];
            $result = apiCall(AddressApi::GET_INFO,[$map,'id desc',false,true]);
        }
        if($result['status']){
            $this->apiReturnSuc($result['info']);
        }else{
            $this->apiReturnErr("获取失败");
        }
    }

    //删除地址
    public function delete(){
        $this->checkVersion($this->api_ver);
        addLog("Address/delete",$_GET,$_POST,"应用" . $this->client_id . "调用Address删除接口");
        $id  = $this->_post('id',0,'缺失地址ID');
        $uid = $this->_post('uid',0,'用户ID缺失');

        $map = ['id'=>$id,'uid'=>$uid];
        $r = apiCall(AddressApi::DELETE,[$map]);
        if(!$r['status'])  $this->apiReturnErr($r['info']);
        if(intval($r['info']) === 0) $this->apiReturnErr("无此地址");
        $map = ['uid'=>$uid];
        $aid = $this->getAidByUid($uid);
        if($aid && $aid == intval($id)){
            //删除了默认地址
            $r = apiCall(AddressApi::GET_INFO,[$map,'id desc']);
            if(!$r['status']) $this->apiReturnErr($r['info']);
            $aid = 0;
            if($r['info'] && isset($r['info']['id'])){
                $aid = intval($r['info']['id']);
            }
            $this->setDefaultAid($uid,$aid);
        }
        $this->apiReturnSuc("删除成功");
    }

    /**
     * 修改收货地址
     */
    public function update(){
        $this->checkVersion($this->api_ver);
        addLog("Address/update",$_GET,$_POST,"应用" . $this->client_id . "调用Address修改接口");

        $id      = $this->_post("id",0,"地址参数ID不能为空");
        $uid     = $this->_post("uid",0,"用户ID不能为空");
        $default = $this->_post("default",0);
        $map     = $this->getAddressUpdate();
        // $map['id'] = $id;
        if(empty($map)) $this->apiReturnErr("未作修改");
        $result = apiCall(AddressApi::GET_INFO,[['id'=>$id]]);
        if(!$result['status']) $this->apiReturnErr("系统错误");
        if(empty($result['info']))  $this->apiReturnErr("无此地址");
        $result = apiCall(AddressApi::SAVE_BY_ID,[$id,$map]);
        if($result['status']){
            if(1 === intval($default))
                $this->setDefaultAid($uid,$id);
            // elseif(0 === intval($default)){
                //禁止修改默认地址 是否默认
                // $aid = $this->getAidByUid($uid);
                // if($aid && $aid==$id){
                //     //trace('取消默认地址');
                // }
            // }
            $this->apiReturnSuc("修改成功");
        }else{
            $this->apiReturnErr("修改失败");
        }
    }

    /**
     * 获取地址信息的接口
     */
    public function getInfo(){
        $this->checkVersion($this->api_ver);
        addLog("Address/getinfo",$_GET,$_POST,"应用" . $this->client_id . "调用Address获取信息接口");

        $id  = $this->_post('id',0,"地址ID不能为空");
        $uid = $this->_post('uid',0,"用户ID不能为空");
        $map = [
          'id'  =>$id,
          'uid' =>$uid
        ];

        $aid    = $this->getAidByUid($uid);
        $result = apiCall(AddressApi::GET_INFO,[$map]);
        if(!$result['status']){
            $this->apiReturnErr($result['info']);
        }else{
            if(empty($result['info'])) $this->apiReturnSuc(['temp'=>'']);
            $result['info']['default'] = ($aid && intval($result['info']['id']) == $aid)?1:0;
            $this->apiReturnSuc($result['info']);
        }
    }

    private function getAidByUid($uid=0){
        $result = apiCall(MemberConfigApi::GET_INFO,[['uid'=>$uid]]);
        if(false === $result['status'])
            $this->apiReturnErr('系统错误: 获取用户配置失败！');
        return empty($result['info'])?0:intval($result['info']['default_address']);
    }

    private function setDefaultAid($uid=0,$aid=0){
        $uid = intval($uid);
        $aid = intval($aid);
        $result = apiCall(MemberConfigApi::SAVE_BY_ID,[$uid,['default_address'=>$aid]]);
        if(!$result['status'])
            $this->apiReturnSuc("设置默认地址失败");
    }
    //--private
    private function getAddressModel(){

        $province    =$this->_post('province','',"省份不能为空");
        $city        =$this->_post('city','',"城市不能为空");
        $area        =$this->_post('area','',"详细地址不能为空");
        $provinceid  =$this->_post('provinceid','',"省份编码不能为空");
        $cityid      =$this->_post('cityid','',"城市编码不能为空");
        $areaid      =$this->_post('areaid','',"地区编码不能为空");
        $detailinfo  =$this->_post('detailinfo','');
        $contactname =$this->_post('contactname','',"联系人不能为空");
        $mobile      =$this->_post('mobile','',"联系电话不能为空");
        $postal_code =$this->_post('postal_code','',"邮政编码不能为空");
        $country     = $this->_post("country",1017);
        $wxno        = $this->_post('wxno','');
        $id_card     = $this->_post("id_card",'');

        $check = new Check();
        if(!empty($id_card) && !$check->is_ID_Card($id_card)){
            $this->apiReturnErr("请填写真实的身份证!");
        }
        //bug fix
        if(1017 == intval($country)) $country = '中国';
        if(86 == intval($country))   $country = '中国';
        $map = [
            'country'     =>$country,
            'city'        =>$city,
            'province'    =>$province,
            'area'        =>$area,
            'detailinfo'  =>$detailinfo,
            'contactname' =>$contactname,
            'mobile'      =>$mobile,
            'postal_code' =>$postal_code,
            'wxno'        =>$wxno,
            'cityid'      =>$cityid,
            'provinceid'  =>$provinceid,
            'areaid'      =>$areaid,
            'id_card'     =>$id_card,
        ];

        return $map;
    }

    private function getAddressUpdate(){

        $province    = $this->_post('province','');
        $city        = $this->_post('city','');
        $area        = $this->_post('area','');
        $provinceid  = $this->_post('provinceid','');
        $cityid      = $this->_post('cityid','');
        $areaid      = $this->_post('areaid','');
        $detailinfo  = $this->_post('detailinfo','');
        $contactname = $this->_post('contactname','');
        $mobile      = $this->_post('mobile','');
        $postal_code = $this->_post('postal_code','');
        $country     = $this->_post("country",1017);
        $wxno        = $this->_post('wxno','');
        $id_card     = $this->_post("id_card",'');

        $check = new Check();
        if(!empty($id_card) && !$check->is_ID_Card($id_card)){
            $this->apiReturnErr("请填写真实的身份证!");
        }
        //bug fix
        if(1017 == intval($country)) $country = '中国';
        if(86 == intval($country))   $country = '中国';
        $map = [
            'country'     =>$country,
            'city'        =>$city,
            'province'    =>$province,
            'area'        =>$area,
            'detailinfo'  =>$detailinfo,
            'contactname' =>$contactname,
            'mobile'      =>$mobile,
            'postal_code' =>$postal_code,
            'wxno'        =>$wxno,
            'cityid'      =>$cityid,
            'provinceid'  =>$provinceid,
            'areaid'      =>$areaid,
            'id_card'     =>$id_card,
        ];

        foreach($map as $key=>$val){
            if($val == '') unset($map[$key]);
        }

        return $map;
    }


}